/*
 * Copyright 2018 Youchaoshi authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain ShareUtil copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package common.plugins.tbs;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.qw.soul.permission.SoulPermission;
import com.qw.soul.permission.bean.Permission;
import com.qw.soul.permission.callbcak.CheckRequestPermissionListener;
import com.tekj.cxqcb.BuildConfig;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;

import java.io.File;
import java.util.UUID;

import es.dmoral.toasty.Toasty;

/**
 * WebChromeClient重写
 * Created by JustTong on 2018/12/11.
 */
public class WebCoreChromeClient extends WebChromeClient {
    Activity mActivity;
    ProgressBar mPbBar;
    ImageView imageLoad;
    String mTitle;
    ValueCallback<Uri[]> uploadMessageAboveL;
    ValueCallback<Uri> uploadMessage;
    String mCameraFilePath;

    public static final int REQUEST_CODE_ALBUM = 0x01;
    public static final int REQUEST_CODE_CAMERA = 0x02;
    public static final int REQUEST_CODE_PERMISSION_CAMERA = 0x03;
    private Thread mThread;

    public WebCoreChromeClient(Activity activity, ProgressBar pbBar, String title) {
        super();

        this.mActivity = activity;
        this.mPbBar = pbBar;
        this.mTitle = title;


    }

    public WebCoreChromeClient(Activity mActivity, ProgressBar mPbBar,
                               String mTitle, ImageView load,
                               ValueCallback<Uri[]> mUploadCallBackAboveL,
                               ValueCallback<Uri> mUploadCallBack,
                               String mCameraFilePath) {
        this.mActivity = mActivity;
        this.mPbBar = mPbBar;
        this.mTitle = mTitle;
        this.uploadMessageAboveL = mUploadCallBackAboveL;
        this.uploadMessage = mUploadCallBack;
        this.mCameraFilePath = mCameraFilePath;
        imageLoad = load;
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        if (mTitle.equals("")) {
            mActivity.setTitle(title);
        } else {
            mActivity.setTitle(mTitle);
        }

    }

    @Override
    public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
        WebCoreJsInterface.Dialogshow(message);
        result.confirm();

        return true;
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        // TODO Auto-generated method stub
        mPbBar.setProgress(newProgress);

        if (mPbBar != null && newProgress != 100) {
//            mPbBar.setVisibility(View.VISIBLE);
            imageLoad.setVisibility(View.VISIBLE);
        } else {
//            mPbBar.setVisibility(View.GONE);
            imageLoad .setVisibility(View.GONE);
        }
    }


    //For Android  >= 4.1
    public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
        uploadMessage = valueCallback;
        uploadPicture();
    }

    // For Android >= 5.0
    @Override
    public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
        uploadMessageAboveL = filePathCallback;
        uploadPicture();
        return true;
    }


    /**
     * 选择相机或者相册
     */
    public void uploadPicture() {

        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setTitle("请选择图片上传方式");

        //取消对话框
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {

                //一定要返回null,否则<input type='file'>
                if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(null);
                    uploadMessage = null;
                }
                if (uploadMessageAboveL != null) {
                    uploadMessageAboveL.onReceiveValue(null);
                    uploadMessageAboveL = null;

                }
            }
        });


        builder.setPositiveButton("相机", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {


                if (!TextUtils.isEmpty(mCameraFilePath)) {
                    //上一张拍照的图片删除
                    mThread = new Thread(new Runnable() {
                        @Override
                        public void run() {

                            File file = new File(mCameraFilePath);
                            if (file != null) {
                                file.delete();
                            }
                            mHandler.sendEmptyMessage(1);

                        }
                    });

                    mThread.start();


                } else {
                    SoulPermission.getInstance().checkAndRequestPermission(Manifest.permission.CAMERA,
                            new CheckRequestPermissionListener() {
                                @Override
                                public void onPermissionOk(Permission permission) {
                                    takePhoto();
                                }

                                @Override
                                public void onPermissionDenied(Permission permission) {
                                    Toasty.normal(mActivity, "缺少拍照权限！").show();
                                }
                            });
                }


            }
        });
        builder.setNegativeButton("相册", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

                chooseAlbumPic();


            }
        });

        builder.create().show();

    }

    /**
     * 拍照
     */
    private void takePhoto() {

        StringBuilder fileName = new StringBuilder();
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        fileName.append(UUID.randomUUID()).append("_upload.png");
        File tempFile = new File(mActivity.getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName.toString());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(mActivity, BuildConfig.APPLICATION_ID, tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            Uri uri = Uri.fromFile(tempFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }

        mCameraFilePath = tempFile.getAbsolutePath();
        mActivity.startActivityForResult(intent, REQUEST_CODE_CAMERA);


    }

    public String getmCameraFilePath() {
        return mCameraFilePath;
    }

    public void setmCameraFilePath(String mCameraFilePath) {
        this.mCameraFilePath = mCameraFilePath;
    }

    public ValueCallback<Uri[]> getUploadMessageAboveL() {
        return uploadMessageAboveL;
    }

    public ValueCallback<Uri> getUploadMessage() {
        return uploadMessage;
    }

    /**
     * 选择相册照片
     */
    private void chooseAlbumPic() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        mActivity.startActivityForResult(Intent.createChooser(i, "Image Chooser"), REQUEST_CODE_ALBUM);

    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            takePhoto();
        }
    };

}
